import React, { useEffect, useRef, useState } from 'react'
import { Checkbox, Form } from 'antd'
import useGetTableData from '@/hooks/useGetTableDataV2NoPagination'
import { getTimeAchieveDashboard } from '@/api/monitor'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useFourColumns, useOneColumns, useThreeColumns, useTwoColumns } from './TableColumns'
import { DashBoardTimeAchieveVO as ITableData } from './types'
import CustomTable from '@/components/QsfCustomTable'
import { useAppSelector } from '@/store/hooks'
import { searchConfig } from './FormConfig'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import useSearchUser from '@/hooks/useSearchUser'
import './index.less'
import useCachePage from '@/hooks/useCachePage'
import { getDefaultYear } from '@/utils/util'
const Index: React.FC = () => {
  const [form] = useForm()
  const [FormMonitor] = useForm()
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const { SupplierOption, setSupplierOption, handleSearchSupplier } = useSearchSupplier('supplierId')
  const { UserOptions, setUserOptions, handleSearchUser } = useSearchUser()
  const [currentSelectKeys, setcurrentSelectKeys] = useState<number[]>([])
  const diffKeys = useRef<number[]>([])
  const { setCachePage, getCachePage } = useCachePage()
  const { tableProps, params, search, reset, reload } = useGetTableData<ITableData>(getTimeAchieveDashboard, {
    form: form,
    immediatelySend: false,
    defaultParams: {
      calculateScope: 0,
    },
    defaultFieldsParams: {
      year: getDefaultYear(),
      productScope: 0,
      orderScope: 0,
      trackPersonGroup: 1,
    },
    paramsCallback: (reqParams) => {
      return {
        ...reqParams,
      }
    },
  })
  const {
    tableProps: tablePropsV1,
    search: searchV1,
    reload: reloadV1,
  } = useGetTableData<ITableData>(getTimeAchieveDashboard, {
    form: form,
    immediatelySend: false,
    defaultParams: {
      calculateScope: 1,
    },
    paramsCallback: (reqParams) => {
      return {
        ...reqParams,
      }
    },
  })
  const {
    tableProps: tablePropsV2,
    search: searchV2,
    reload: reloadV2,
  } = useGetTableData<ITableData>(getTimeAchieveDashboard, {
    form: form,
    defaultParams: {
      calculateScope: 2,
    },
    immediatelySend: false,
    paramsCallback: (reqParams) => {
      return {
        ...reqParams,
      }
    },
  })
  const {
    tableProps: tablePropsV3,
    search: searchV3,
    reload: reloadV3,
  } = useGetTableData<ITableData>(getTimeAchieveDashboard, {
    form: form,
    immediatelySend: false,
    defaultParams: {
      calculateScope: 3,
    },
    paramsCallback: (reqParams) => {
      return {
        ...reqParams,
      }
    },
  })
  useEffect(() => {
    handleCacheData()
  }, [])
  useEffect(() => {
    diffKeys.current.includes(0) && search()
    diffKeys.current.includes(1) && searchV1()
    diffKeys.current.includes(2) && searchV2()
    diffKeys.current.includes(3) && searchV3()
  }, [diffKeys.current])
  const handleCacheData = async () => {
    const cacheData = getCachePage()
    if (cacheData == null) {
      await form.validateFields()
      search()
      setCachePage({ ...params, selectKeys: [0] })
      setcurrentSelectKeys([0])
    } else {
      form.resetFields()
      form.setFieldsValue({
        ...cacheData,
      })
      setSupplierOption(cacheData?.SupplierOption || [])
      setUserOptions(cacheData?.UserOptions || [])
      const { SupplierOption, UserOptions, selectKeys, ...resetCacheData } = cacheData
      setcurrentSelectKeys(selectKeys || [])
      FormMonitor.setFieldValue('selectKeys', selectKeys || [])
      selectKeys?.includes(0) && reload({ ...resetCacheData, calculateScope: 0 })
      selectKeys?.includes(1) && reloadV1({ ...resetCacheData, calculateScope: 1 })
      selectKeys?.includes(2) && reloadV2({ ...resetCacheData, calculateScope: 2 })
      selectKeys?.includes(3) && reloadV3({ ...resetCacheData, calculateScope: 3 })
    }
  }
  return (
    <PageContainer className="monitor_returntime_wrap">
      <SearchForm
        params={params}
        form={form}
        searchConfig={searchConfig({
          DICTDATA,
          SupplierOption,
          handleSearchSupplier,
          UserOptions,
          handleSearchUser,
        })}
        onFinish={async () => {
          currentSelectKeys.includes(0) && search()
          currentSelectKeys.includes(1) && searchV1()
          currentSelectKeys.includes(2) && searchV2()
          currentSelectKeys.includes(3) && searchV3()
          setCachePage({
            ...form.getFieldsValue(),
            selectKeys: currentSelectKeys,
            SupplierOption,
            UserOptions,
          })
        }}
        onReset={() => {
          reset()
          FormMonitor.setFieldValue('selectKeys', [0])
          setCachePage({ selectKeys: [0], year: getDefaultYear(), productScope: 0, orderScope: 0, trackPersonGroup: 1 })
          setcurrentSelectKeys([0])
        }}
        extra={
          <div className="table_extra_flex_wrapbox">
            <div className="table_extra_flex">
              <Form form={FormMonitor} className="suggestion_form" initialValues={{ selectKeys: [0] }}>
                <span style={{ fontWeight: 800, marginRight: 8 }}>时效监控：</span>
                <Form.Item noStyle name="selectKeys">
                  <Checkbox.Group
                    onChange={(selectKeys) => {
                      const diff = selectKeys.filter((item) => !currentSelectKeys?.includes(item))
                      diffKeys.current = diff
                      const cacheData = getCachePage()
                      setcurrentSelectKeys(selectKeys)
                      setCachePage({
                        ...cacheData,
                        selectKeys,
                      })
                    }}
                    options={[
                      {
                        label: '总周期',
                        value: 0,
                      },
                      {
                        label: '面料周期-集约',
                        value: 1,
                      },
                      {
                        label: '面料周期-非集约',
                        value: 2,
                      },
                      {
                        label: '生产周期',
                        value: 3,
                      },
                    ]}
                  />
                </Form.Item>
              </Form>
            </div>
            <div className="table_extra_flex"></div>
          </div>
        }
      ></SearchForm>
      {currentSelectKeys.includes(0) ? (
        <div className="returntime_table_box">
          <div className="rtb_title">总周期</div>
          <div className="rtb_main">
            <CustomTable
              className="mini_table_custom_style"
              stripe={false}
              isAutoScrollY={false}
              columns={useOneColumns()}
              {...tableProps}
              rowKey={(rows) => rows.bigClassName}
              pagination={false}
              tableRowGray={(record) => (record?.bigClassName == '合计' ? 'qsf_custom_table_bgc_grey' : '')}
            />
          </div>
        </div>
      ) : null}
      {currentSelectKeys.includes(1) ? (
        <div className="returntime_table_box">
          <div className="rtb_title">面料周期-集约</div>
          <div className="rtb_main">
            <CustomTable
              className="mini_table_custom_style"
              stripe={false}
              isAutoScrollY={false}
              columns={useTwoColumns()}
              {...tablePropsV1}
              rowKey={(rows) => rows.bigClassName}
              pagination={false}
              tableRowGray={(record) => (record?.bigClassName == '合计' ? 'qsf_custom_table_bgc_grey' : '')}
            />
          </div>
        </div>
      ) : null}
      {currentSelectKeys.includes(2) ? (
        <div className="returntime_table_box">
          <div className="rtb_title">面料周期-非集约</div>
          <div className="rtb_main">
            <CustomTable
              className="mini_table_custom_style"
              stripe={false}
              isAutoScrollY={false}
              columns={useThreeColumns()}
              {...tablePropsV2}
              rowKey={(rows) => rows.bigClassName}
              pagination={false}
              tableRowGray={(record) => (record?.bigClassName == '合计' ? 'qsf_custom_table_bgc_grey' : '')}
            />
          </div>
        </div>
      ) : null}
      {currentSelectKeys.includes(3) ? (
        <div className="returntime_table_box">
          <div className="rtb_title">生产周期</div>
          <div className="rtb_main">
            <CustomTable
              className="mini_table_custom_style"
              stripe={false}
              isAutoScrollY={false}
              columns={useFourColumns()}
              {...tablePropsV3}
              rowKey={(rows) => rows.bigClassName}
              pagination={false}
              tableRowGray={(record) => (record?.bigClassName == '合计' ? 'qsf_custom_table_bgc_grey' : '')}
            />
          </div>
        </div>
      ) : null}
    </PageContainer>
  )
}

export default Index
